package com.younion.action.manage;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.younion.business.ICostService;
import com.younion.common.base.BaseAction;
import com.younion.common.constants.CostType;
import com.younion.common.constants.TemplateTargetType;
import com.younion.common.exception.BaseException;
import com.younion.common.exception.BusinessException;
import com.younion.common.paginator.Paginator;
import com.younion.util.YounionUtil;
import com.younion.vo.CostVO;
import com.younion.vo.CustomerVO;
import com.younion.vo.MemberCardVO;
import com.younion.vo.MembercardServiceVO;
import com.younion.vo.ProductVO;

import cpcns.jhsks.util.MapCollectionUtils;

/**
 * @author wells
*/
public class CostAction extends BaseAction {

	private static final long serialVersionUID = 1L;

	protected static final Log logger = LogFactory.getLog(CostAction.class);

	private ICostService costService = null;
	
	private CostVO costVO = new CostVO();
	
	private List<CostType> costTypes = Arrays.asList(CostType.values());

	private List<CostVO> costList;// 结果集列表
	private String searchType;
	
	/**
	 * 列表：翻页区；数据区
	 */
	@SuppressWarnings("unchecked")
	public String listCost() {
		try {
			Map paramMap = null;
			if (costVO != null) {
				if(costVO.getCustomerId() != null){
					costVO.setCustomer(new CustomerVO(costVO.getCustomerId()));
				}else if(getSessionUser().getCustomer() != null){
					costVO.setCustomer(getSessionUser().getCustomer());
				}
				paramMap = MapCollectionUtils.removeEmptyEntry(PropertyUtils.describe(costVO));
			}
			// 获取总记录数
			int total = costService.getCountByMap(paramMap);
			// 根据总记录数获取分页对象
			Paginator paginator = this.getPaginator(total);
			costList = costService.get(paramMap, paginator);
			// 保存分页对象
			this.savaPaginator(paginator);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return SUCCESS;
	}

	/**
	 * 新增
	 */
	public String addCost() {
		try {
			costVO.setCardEntity(getMemberCardService().getById(costVO.getCardEntity().getId().toString())) ;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}

	/**
	 * 修改保存，调度Jsp
	 */
	public String editCost() {
		try {
			costVO = costService.getById(costVO.getId().toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}

	/**
	 * 保存动作
	 */
	public String saveCost() {
		try {
			costVO.setCostDate(new Date());
			costVO.setOperator(getSessionUser());
			if(costVO.getProduct() == null)
				costVO.setProduct(new ProductVO(costVO.getProductId()));
			costVO = costService.save(costVO);		
			sendCostNotification();
		} catch (Exception e) {
			if(e instanceof BusinessException){
				tipMessage = e.getMessage();
			}else{
				tipMessage = "消费发生出错！";
				e.printStackTrace();
			}
			request.setAttribute("tipMessage", tipMessage);
			return ERROR;
		}
		request.setAttribute("refreshNavTabId", "costList");
		request.setAttribute("callbackType", "forward");
		request.setAttribute("forwardUrl", request.getContextPath()+"/cost/listCost.action");
		return SUCCESS;
	}

	private void sendCostNotification() throws Exception, BaseException {
		if(CostType.SCORE.getName().equals(costVO.getType())){
			MemberCardVO card = memberCardService.getById(costVO.getCardEntity().getId().toString());
			MembercardServiceVO service = retreiveMemberCardService(card, TemplateTargetType.COSTSCORE);
			if(service != null){
				String content = YounionUtil.generateMessageContent(service.getTemplate().getContent(), service.getMemberCard());
				content = YounionUtil.generateChangeData(content, null, null, null, costVO.getScore(), null, null,costVO.getMoney());
				if(costVO.getProductName() != null){
					content = YounionUtil.generateMessageContentByProduct(content, costVO.getProductName());
				}
				sendNotification(service,TemplateTargetType.COSTSCORE, content);
			}
		}else{
			MemberCardVO card = memberCardService.getById(costVO.getCardEntity().getId().toString());
			MembercardServiceVO service = retreiveMemberCardService(card, TemplateTargetType.COST);
			if(service != null){
				String content = YounionUtil.generateMessageContent(service.getTemplate().getContent(), service.getMemberCard());
				content = YounionUtil.generateChangeData(content, null, null, null, costVO.getScore(), null, null,costVO.getMoney());
				if(costVO.getProductName() != null){
					content = YounionUtil.generateMessageContentByProduct(content, costVO.getProductName());
				}
				sendNotification(service,TemplateTargetType.COST, content);
			}
		}
	}

	/**
	 * 删除
	 */
	public String deleteCost() {
		try {
			String pkId = request.getParameter("key");
			costService.remove(Arrays.asList(pkId.split(",")));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		request.setAttribute("refreshNavTabId", "costList");
		return SUCCESS;
	}
	/**
	 * 查看鿴
	 */
	public String viewCost() {
		try {
			String pkId = request.getParameter("key"); 
			costVO = costService.getById(pkId);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		return SUCCESS;

	}

	public CostVO getCostVO() {
		return costVO;
	}

	public void setCostVO(CostVO costVO) {
		this.costVO = costVO;
	}

	public void setCostService(ICostService costService) {
		this.costService = costService;
	}

	public List<CostVO> getCostList() {
		return costList;
	}

	public void setCostList(List<CostVO> costList) {
		this.costList = costList;
	}

	public List<CostType> getCostTypes() {
		return costTypes;
	}

	public void setCostTypes(List<CostType> costTypes) {
		this.costTypes = costTypes;
	}

	public ICostService getCostService() {
		return costService;
	}

	public String getSearchType() {
		return searchType;
	}

	public void setSearchType(String searchType) {
		this.searchType = searchType;
	}
	
}